package com.fivefu.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.fivefu.core.exception.FfSqlAnalysisException;
import com.fivefu.core.param.FFTableMapperParam;
import com.fivefu.core.pojo.FfSql;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

/**
 * @Author zhf
 * @Description 处理On
 * @Date 2021/3/12
 */
@Component
public class OnSqlHandler implements  SqlHandler {
    private static String LEFT_JOIN = " left JOIN  ";
    @Override
    public void dealSql(JSONObject jsonObject, FfSql ffSql) throws FfSqlAnalysisException {
        if (ffSql.getUnProcessedTableNameList().size() > 1) {
            //多表进行处理
            StringBuffer stringBuffer = new StringBuffer();
            HashSet<String> hashSet = new HashSet();

            List<String> tablenameList = ffSql.getUnProcessedTableNameList();
            for (String s : tablenameList) {
                JSONObject tableObject = jsonObject.getJSONObject(FFTableMapperParam.getExposeTableName(s));
                for (Map.Entry entry : tableObject.entrySet()) {
                    String key = entry.getKey().toString();
                    if (key.endsWith("@")) {
                        String path = entry.getValue().toString().toLowerCase();

                        String relaColumn = entry.getKey().toString().substring(0, key.length() - 1);
                        String arr[] = path.split("/");
                        if (arr.length == 2) {
                            //默认左连接
                            stringBuffer.append(" ").append(s)
                                    .append(LEFT_JOIN)
                                    .append(FFTableMapperParam.getOriginTableName(arr[0]))
                                    .append(" on ")
                                    .append(s).append(".").append(relaColumn)
                                    .append(" = ")
                                    .append(FFTableMapperParam.getOriginTableName(arr[0])).append(".").append(arr[1]);
                        }
                        tableObject.remove(key);
                        break;
                    }
                }
            }

            ffSql.setTablename(stringBuffer.toString());
        }
    }

    @Override
    public int order() {
        return 2;
    }

    private String errorMsg;

    @Override
    public String getErrMsg() {
        return this.errorMsg;
    }

    protected void setErrorMsg(String msg){
        this.errorMsg = msg;
    }
}
